package com.longrise.android.loaddata.newloaddata;

/**
 * Created by chengsan on 16/6/16.
 */
import android.content.Context;

import com.longrise.android.util.IntenetUtil;
import com.longrise.android.util.Util;

import java.io.File;

public class ConfigCache
{
    private static final String TAG = ConfigCache.class.getName();

    public static String getUrlCache(String url, String cacheDic, Context context,int mobileTimeOut,int wifiTimeOut)
    {
        if(url == null || url.isEmpty() || cacheDic == null || cacheDic.isEmpty() || context == null)
        {
            return  null;
        }


        String result = null;

        File file = new File(cacheDic + "/" + getCacheDecodeString(url));
        //判断文件是否存在
        if(file.exists() && file.isFile())
        {
            long expiredTime = System.currentTimeMillis() - file.lastModified();

            if(IntenetUtil.getNetworkState(context) != IntenetUtil.NETWORN_NONE && expiredTime < 0)
            {
                return null;
            }

            if(IntenetUtil.getNetworkState(context) == IntenetUtil.NETWORN_WIFI && expiredTime > wifiTimeOut)
            {
                return null;
            }
            else if (IntenetUtil.getNetworkState(context) == IntenetUtil.NETWORN_MOBILE
                    && expiredTime > mobileTimeOut)
            {
                return null;
            }

            result = Util.read(file.getPath(),context);
        }

        return  result;
    }


    /**
     * 写入缓存
     * @param data
     * @param url
     * @param cacheDic
     */
    public static void setUrlCache(String data, String url,String cacheDic,Context context)
    {
        File file = new File(cacheDic + "/" + getCacheDecodeString(url));
        //创建缓存数据到磁盘，就是创建文件
        Util.write(file.getPath(),data,context);
    }



    public static String getCacheDecodeString(String url)
    {
        //1. 处理特殊字符
        //2. 去除后缀名带来的文件浏览器的视图凌乱(特别是图片更需要如此类似处理，否则有的手机打开图库，全是我们的缓存图片)
        if (url != null)
        {
            return url.replaceAll("[.:/,%?&=]", "+").replaceAll("[+]+", "+");
        }
        return null;
    }
}
